#!/usr/bin/env bash

# 从 Docker 镜像 复制二进制文件，安装 PHP Redis Memcached

ScriptRoot="$( cd "$( dirname "$0"  )" && pwd  )"

source $ScriptRoot/../.env.example

PHP_LATEST_STABLE_VERSION=${LNMP_PHP81_VERSION}

_print_help_info(){
    exec echo "

Install WSL soft by shell script


Usage:

$ lnmp-wsl-install php ${PHP_LATEST_STABLE_VERSION} [ tar | deb | rpm ]

$ lnmp-wsl-install enable [ php81 | php80 | php74 | php73 | php72 | php71 | php70 | php56 ]

$ lnmp-wsl-install mysql php go node postgresql mongodb swift

$ lnmp-wsl-install enable nginx httpd

$ lnmp-wsl-install php-extension-list

Example:

$ lnmp-wsl-install php ${PHP_LATEST_STABLE_VERSION} tar

$ lnmp-wsl-install php ${PHP_LATEST_STABLE_VERSION} deb

$ lnmp-wsl-install php ${PHP_LATEST_STABLE_VERSION} rpm

$ lnmp-wsl-install php ${PHP_LATEST_STABLE_VERSION} [${LNMP_PHP80_VERSION}] [${LNMP_PHP74_VERSION}] [${LNMP_PHP73_VERSION}] [${LNMP_PHP72_VERSION}] [${LNMP_PHP71_VERSION}] [${LNMP_PHP70_VERSION}] [${LNMP_PHP56_VERSION}]

$ REGISTRY_MIRROR=mirror.baidubce.com  lnmp-wsl-install php nightly

$ REGISTRY_MIRROR=hub-mirror.c.163.com lnmp-wsl-install php nightly

[ php56 只支持 ubuntu ]
"

}

if [ -n "$debug" -o -n "$DEBUG" ];then set -x ;fi

source /etc/os-release

################################################################################

SWIFT_PREFIX=/usr/local/swift

PG_MAJOR=10

GO_PREFIX=/usr/local

GO_VERSION=1.20.1

NODE_VERSION=18.2.0

NODE_PREFIX=/usr/local

PHP_VERSION=${PHP_LATEST_STABLE_VERSION}

MYSQL_DEB_VERSION=0.8.13-1

SWIFT_VERSION=5.2.5

################################################################################
_sudo(){
  command -v sudo > /dev/null && echo "sudo" || true
}

_httpd(){
  echo "Please exec $ lnmp-wsl-builder-httpd.py"
}

_nginx(){
  echo "Install NGINX by apt already remove. Please exec $ lnmp-wsl-builder-nginx.py"
  echo
  return
  # apt
  if ! [ -f /etc/apt/sources.list.d/nginx.list ];then
    set +x
    echo "deb http://nginx.org/packages/mainline/${ID} ${VERSION_CODENAME} nginx" | \
        $(_sudo) tee /etc/apt/sources.list.d/nginx.list
    set -x
  fi

  apt-key list | grep nginx || curl -fsSL http://nginx.org/packages/keys/nginx_signing.key | $(_sudo) apt-key add -

  $(_sudo) apt update

  $(_sudo) apt install -y nginx

  if ! [ -h /etc/nginx/conf.d ];then $(_sudo) rm -rf /etc/nginx/conf.d; \
      $(_sudo) ln -sf $WSL_HOME/lnmp/wsl/nginx /etc/nginx/conf.d; fi

  # apt install nginx notinclude fastcgi.conf
  if ! [ -f /etc/nginx/fastcgi.conf ];then $(_sudo) cp $WSL_HOME/lnmp/config/etc/nginx/fastcgi.conf \
      /etc/nginx/fastcgi.conf ; fi

  $(_sudo) nginx -T | grep "fastcgi_buffering off;" || $(_sudo) cp $WSL_HOME/lnmp/wsl/config/nginx.wsl.conf /etc/nginx/nginx.conf

  $(_sudo) nginx -t

}

_php(){
  # include redis memcached

  PHP_VERSION=${1:-${PHP_LATEST_STABLE_VERSION}}

  case ${PHP_VERSION} in
    5.6.* )
      export PHP_NUM=56
      ;;

    7.0.* )
      export PHP_NUM=70
      ;;

    7.1.* )
      export PHP_NUM=71
      ;;

    7.2.* )
      export PHP_NUM=72
      ;;

    7.3.* )
      export PHP_NUM=73
      ;;

    7.4.* )
      export PHP_NUM=74
      ;;

    8.0.* )
      export PHP_NUM=80
      ;;

    8.1.* )
      export PHP_NUM=81
      ;;

    nightly )
      export PHP_NUM=82
      PHP_VERSION=0.0.0
      ;;

    * )
      echo "ONLY SUPPORT 5.6.x 7.0.x 7.1.x 7.2.x 7.3.x 7.4.x 8.0.x 8.1.x nightly"
      exit 1
  esac

################################################################################

  PHP_PREFIX=/usr/local/php${PHP_NUM}
  PHP_INI_DIR=/usr/local/etc/php${PHP_NUM}

_tar(){
# debian ubuntu
TAR_IMAGE=khs1994/wsl
TAR_TAG=khs1994-wsl-php${PHP_NUM}_${PHP_VERSION}-${ID}-"${VERSION_CODENAME}"_amd64

if [ "$ID" = 'centos' -o "$ID" = 'fedora' -o "$ID" = 'rocky' ];then
  # rhel
  # TAR_IMAGE=khs1994/wsl
  TAR_TAG=khs1994-wsl-php${PHP_NUM}_${PHP_VERSION}-${ID}-${VERSION_ID}_amd64
fi

# docker pull ${TAR_IMAGE}:${TAR_TAG}

# docker create --name=${CONTAINER_NAME} ${TAR_IMAGE}:${TAR_TAG} command

# rm
$(_sudo) rm -rf ${PHP_PREFIX}

# docker cp ${CONTAINER_NAME}:/php${PHP_NUM}.tar.gz /tmp

# docker rm -f ${CONTAINER_NAME}

dist=`$ScriptRoot/../windows/sdk/dockerhub/rootfs.sh ${TAR_IMAGE} ${TAR_TAG}`

$(_sudo) tar -zxvf $dist -C /tmp

# backup
if [ -d ${PHP_INI_DIR} ];then
  $(_sudo) mv ${PHP_INI_DIR} ${PHP_INI_DIR}.$( date +%s ).backup
fi

$(_sudo) tar -zxvf /tmp/php${PHP_NUM}.tar.gz -C /usr/local

$(_sudo) rm -rf /tmp/php${PHP_NUM}.tar.gz

# log
cd /var/log

if ! [ -f php${PHP_NUM}.error.log ];then $(_sudo) touch php${PHP_NUM}.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.error.log ];then $(_sudo) touch php${PHP_NUM}-fpm.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.access.log ];then $(_sudo) touch php${PHP_NUM}-fpm.access.log ; fi
if ! [ -f php${PHP_NUM}-fpm.slow.log ];then $(_sudo) touch php${PHP_NUM}-fpm.slow.log; fi

$(_sudo) chmod 777 php${PHP_NUM}*

# ln
for file in $( ls ${PHP_PREFIX}/bin ); do $(_sudo) ln -sf ${PHP_PREFIX}/bin/$file /usr/local/bin/ ; done

$(_sudo) ln -sf ${PHP_PREFIX}/sbin/* /usr/local/sbin

echo "
Please Exec this command install dep

lnmp-wsl-builder-php apt/yum

"
}

_deb(){
    cd /tmp

    DEB_NAME=khs1994-wsl-php${PHP_NUM}_${PHP_VERSION}-${ID}-${VERSION_CODENAME}_amd64

    $(_sudo) rm -rf ${DEB_NAME}.deb

    # docker pull khs1994/wsl:${DEB_NAME}

    # docker create --name=${CONTAINER_NAME} khs1994/wsl:${DEB_NAME} command

    # docker cp ${CONTAINER_NAME}:/${DEB_NAME}.deb .

    # docker rm -f ${CONTAINER_NAME}

    dist=`$ScriptRoot/../windows/sdk/dockerhub/rootfs.sh khs1994/wsl ${DEB_NAME} '' '' '' 1`

    $(_sudo) tar -zxvf $dist -C /tmp

    $(_sudo) dpkg -i ${DEB_NAME}.deb || ( $(_sudo) apt install -f && $(_sudo) dpkg -i ${DEB_NAME}.deb || true )
}

_rpm(){
  cd /tmp

  RPM_NAME=khs1994-wsl-php-${PHP_VERSION}-1.el${VERSION_ID}.centos.x86_64.rpm

  DOCKER_IMAGE_NAME=khs1994-wsl-php${PHP_NUM}_${PHP_VERSION}-${ID}-${VERSION_ID}_amd64

  $(_sudo) rm -rf ${RPM_NAME}

  # docker pull khs1994/wsl:${DOCKER_IMAGE_NAME}

  # docker create --name=${CONTAINER_NAME} khs1994/wsl:${DOCKER_IMAGE_NAME} command

  # docker cp ${CONTAINER_NAME}:/${RPM_NAME} .

  # docker rm -f ${CONTAINER_NAME}

  dist=`$ScriptRoot/../windows/sdk/dockerhub/rootfs.sh khs1994/wsl ${DOCKER_IMAGE_NAME} '' '' '' 1`

  $(_sudo) tar -zxvf $dist -C /tmp

  $(_sudo) yum install -y ${RPM_NAME}
}

if [ -z "$2" ];then

echo -e "Install php from tar (default)"

_tar

else

echo -e "Install php from $2"

_"$2"

fi

echo "##########################################################################"

php -v

php-fpm -v

echo "##########################################################################"

php -i | grep .ini

# composer cn mirror

command -v /usr/local/bin/composer && composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/ || true

}

_postgresql(){
  # apt
  #
  # @link https://www.postgresql.org/download/linux/debian/

 if ! [ -f /etc/apt/sources.list.d/postgresql.list ];then
    # echo "deb http://apt.postgresql.org/pub/repos/apt/ ${VERSION_CODENAME}-pgdg main" | \
    echo "deb http://mirrors.ustc.edu.cn/postgresql/repos/apt/ ${VERSION_CODENAME}-pgdg main" | \
      $(_sudo) tee /etc/apt/sources.list.d/postgresql.list

    apt-key list | grep PostgreSQL || \
        wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | $(_sudo) apt-key add -

    $(_sudo) apt-get update
 fi

  $(_sudo) apt-get -y install postgresql

  if ! [ -f /usr/share/postgresql/postgresql.conf.sample  ];then
    $(_sudo) mv -v "/usr/share/postgresql/$PG_MAJOR/postgresql.conf.sample" /usr/share/postgresql/

    $(_sudo) ln -sv /usr/share/postgresql/postgresql.conf.sample "/usr/share/postgresql/$PG_MAJOR/"

    $(_sudo) sed -ri "s!^#?(listen_addresses)\s*=\s*\S+.*!\1 = '*'!" /usr/share/postgresql/postgresql.conf.sample
  fi

  env | grep /usr/lib/postgresql/$PG_MAJOR/bin || echo "PATH=\$PATH:/usr/lib/postgresql/$PG_MAJOR/bin" | $(_sudo) tee -a /etc/profile

}

_rabbitmq(){
  # apt
  true
}

_mongodb(){
  # apt
  #
  # @link https://docs.mongodb.com/master/tutorial/install-mongodb-on-debian/
  $(_sudo) apt install mongodb
}

_mysql(){
  # apt
  apt show mysql-apt-config > /dev/null
  if ! [ $? -eq 0 ];then
      wget https://dev.mysql.com/get/mysql-apt-config_${MYSQL_DEB_VERSION}_all.deb
      $(_sudo) dpkg -i mysql-apt-config_${MYSQL_DEB_VERSION}_all.deb
      $(_sudo) apt install -f
      $(_sudo) apt update
  fi

  $(_sudo) apt install -y mysql-server
}

_php-extension-list(){
  # list php extension
  if ! [ -d /usr/local/src/php-${PHP_VERSION}/ext ];then
    echo "php src not found"
    return;
  fi
  cd /usr/local/src/php-${PHP_VERSION}/ext
  set +x
  for ext in `ls`; do echo '*' $( php -r "if(extension_loaded('$ext')){echo '[x] $ext';}else{echo '[ ] $ext';}" ); done
}

_enable(){
  if [ "$1" = nginx ];then
    # /usr/local/nginx self build nginx

    if [ -d /usr/local/nginx ];then
      if ! [ -h /usr/local/etc/nginx/conf.d ];then $(_sudo) rm -rf /usr/local/etc/nginx/conf.d; \
          $(_sudo) ln -sf $WSL_HOME/lnmp/wsl/nginx /usr/local/etc/nginx/conf.d; fi
      # test main conf
      $(_sudo) /usr/local/sbin/nginx -T | grep "fastcgi_buffering off;" || $(_sudo) cp $WSL_HOME/lnmp/wsl/config/nginx.wsl.conf /usr/local/etc/nginx/nginx.conf
      $(_sudo) /usr/local/sbin/nginx -t
    fi
    exit $?
  fi

  PHP_PREFIX=/usr/local/$1

  php_num=$( echo $1 | cut -d 'p' -f 3 )

  if ! [ -d ${PHP_PREFIX} ];then echo -e "\n\n$PHP_PREFIX not exists\n\n"; exit 1; fi

  if [ $(command -v update-alternatives > /dev/null 2>&1 ; echo $?) = 0  ];then
    $(_sudo) update-alternatives --install /usr/local/bin/php php $PHP_PREFIX/bin/php $php_num
    $(_sudo) update-alternatives --install /usr/local/bin/phar phar $PHP_PREFIX/bin/phar $php_num
    $(_sudo) update-alternatives --install /usr/local/bin/php-cgi php-cgi $PHP_PREFIX/bin/php-cgi $php_num
    $(_sudo) update-alternatives --install /usr/local/bin/php-config php-config $PHP_PREFIX/bin/php-config $php_num
    $(_sudo) update-alternatives --install /usr/local/bin/phpize phpize $PHP_PREFIX/bin/phpize $php_num
    $(_sudo) update-alternatives --install /usr/local/sbin/php-fpm php-fpm $PHP_PREFIX/sbin/php-fpm $php_num

    $(_sudo) update-alternatives --set php $PHP_PREFIX/bin/php
    $(_sudo) update-alternatives --set phar $PHP_PREFIX/bin/phar
    $(_sudo) update-alternatives --set php-cgi $PHP_PREFIX/bin/php-cgi
    $(_sudo) update-alternatives --set php-config $PHP_PREFIX/bin/php-config
    $(_sudo) update-alternatives --set phpize $PHP_PREFIX/bin/phpize
    $(_sudo) update-alternatives --set php-fpm $PHP_PREFIX/sbin/php-fpm

    return
  fi

  for file in $( ls ${PHP_PREFIX}/bin ); do
    $(_sudo) ln -sf ${PHP_PREFIX}/bin/$file /usr/local/bin/
  done

  $(_sudo) ln -sf ${PHP_PREFIX}/sbin/php-fpm /usr/local/sbin

  # $(_sudo) sed -i "s#/var/run/php${php_num}-fpm.sock#/var/run/php-fpm.sock#g" \
  #     /usr/local/etc/php${php_num}/php-fpm.d/zz-${ID}.conf
  #
  # $(_sudo) sed -i "s#/var/run/php${php_num}-fpm.pid#/var/run/php-fpm.pid#g" \
  #     /usr/local/etc/php${php_num}/php-fpm.d/zz-${ID}.conf
}

_swift(){
  source /etc/os-release
  if [ "${UBUNTU_CODENAME}" != 'xenial' \
    -a "${UBUNTU_CODENAME}" != 'bionic' \
    -a "${UBUNTU_CODENAME}" != 'focal' \
    -a "${UBUNTU_CODENAME}" != 'focal' \
     ]; then set +x ; echo -e "\nOnly Support Ubuntu 16.04/18.04/20.04/22.04\n"; exit 1; fi

  $(_sudo) apt install -y clang libicu-dev

  cd /tmp
  test -f swift-${SWIFT_VERSION}-RELEASE-ubuntu${VERSION_ID}.tar.gz || \
      wget https://swift.org/builds/swift-${SWIFT_VERSION}-release/ubuntu${VERSION_ID/./''}/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu${VERSION_ID}.tar.gz
  $(_sudo) rm -rf $SWIFT_PREFIX ; $(_sudo) mkdir -p $SWIFT_PREFIX
  $(_sudo) tar --strip=1 -zxvf swift-${SWIFT_VERSION}-RELEASE-ubuntu${VERSION_ID}.tar.gz -C $SWIFT_PREFIX
  $(_sudo) ln -sf $SWIFT_PREFIX/usr/bin/* /usr/local/bin

  swift --version
}

_downloader(){
  path=$1
  install_file=$2
  url=$3
  target_path=$4
  strip=${5:-0}

  if ! [ -d $path ];then

    if ! [ -f /tmp/$install_file ];then
      cd /tmp

      wget $url
    fi

    $(_sudo) tar --strip=${strip} -zxvf /tmp/$install_file -C $target_path

    shift 5

    $(_sudo) $@
fi
}

_go(){
  _downloader ${GO_PREFIX}/go go${GO_VERSION}.linux-amd64.tar.gz \
      https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz \
      $GO_PREFIX

  echo "

vi ~/.bashrc

export GOROOT=${GO_PREFIX}/go

export PATH=${GO_PREFIX}/go/bin:\$PATH

"

}

_node(){
  local realname=node-v${NODE_VERSION}-linux-x64
  local filename=${realname}.tar.gz

  $(_sudo) mkdir -p ${NODE_PREFIX}/node

  _downloader ${NODE_PREFIX}/node/bin ${filename} \
      https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/v${NODE_VERSION}/${filename} \
      ${NODE_PREFIX}/node \
      1

  mkdir -p $HOME/.npm
  $(_sudo) chown -R $USER:$USER $HOME/.npm

  . ~/.bashrc

  node -v || ( \
    echo "export PATH=$HOME/.npm/bin:${NODE_PREFIX}/node/bin:\$PATH" >> ~/.bashrc \
    ; source ~/.bashrc \
    ; node -v )

  source $HOME/.npmrc || true

  test -z "$registry" && echo "registry=https://registry.npmmirror.com" >> ~/.npmrc || true
  test -z "$prefix" && echo "prefix=$HOME/.npm" >> ~/.npmrc || true
}

################################################################################

if [ -z "$1" ];then _print_help_info ; fi

if [ "$debug" = 'true' ];then set -x; fi

set -e

. /etc/os-release

. ~/.bashrc || true

if [ -z "$WSL_HOME" ];then echo "env WSL_HOME not set" ; fi

if [ "$1" = 'enable' ];then shift ; _enable "$@" ; exit $? ; fi

CONTAINER_NAME=$( date +%s )

if [ "$1" = "php" ];then shift ; _php "$@" ; exit $? ; fi

for soft in "$@"; do _$soft || (clear; echo "not support $soft"); done
